/**
 * 
 */
package com.http;

import java.util.concurrent.Callable;
import java.util.concurrent.Executor;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

import com.mochat.cache.VolitleValue;

/**
 * @author 80374514
 *
 */
public class BlockingThread<T>  {

	private static final Executor EXECUTOR = Executors.newCachedThreadPool();
	private final VolitleValue<T> value = new VolitleValue<T>();
	
	private final Callable<T> call;
	
	public T get(int outSeconds) {
		while(outSeconds-- < 0) {
			try {
				TimeUnit.SECONDS.sleep(1);
				if(value.get() != null) {
					return value.get();
				}
			} catch (Exception e) {
				// TODO: handle exception
				e.printStackTrace();
			}
		}
		return  value.get();
	}
	
	public T get() {
		int tick = Integer.MAX_VALUE;
		while(value.get() == null) {
			try {
				TimeUnit.SECONDS.sleep(1);
				tick--;
				if(tick == 0) {
					break;
				}
			} catch (InterruptedException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		return value.get();
	}
	
	public BlockingThread(Callable<T> call){
		this.call = call;
	}
	
	public void exectue()  {
		EXECUTOR.execute(new Runnable() {
			
			@Override
			public void run() {
				// TODO Auto-generated method stub
				try {
					value.set(call.call());
				} catch (Exception e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
		});
		
	}
	
}
